<template>
  <div class="spend">
    <el-card>
      <!-- 付费情况 -->
      <div class="payfee">
        <h3>付费情况</h3>
        <el-row style="margin-bottom: 20px">
          <el-col class="flexCenter" :span="14" style="display: flex">
            <span style="width: 100px">时间区间:</span>
            <div class="time">
              <el-date-picker
                class="dt"
                size="small"
                v-model="search.orderAllTime"
                @change="selectTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
              <span
                v-show="search.orderStartTime || search.orderEndTime"
              ></span>
            </div>
          </el-col>

          <el-form style="display: flex" :model="ruleForm" :rules="rules">
            <el-form-item
              style="
                flex-direction: row;
                width: 400px;
                position: relative;
                left: -113px;
                top: 20px;
              "
              prop="step"
            >
              <el-col :span="124" prop="ruleForm.step" style="margin-top: -4px">
                <span style="width: 120px">价格步长:</span>
                <el-input
                  style="width: 90px; margin-left: 15px"
                  required
                  size="small"
                  v-model="ruleForm.step"
                  @keyup.native="provingstep(index)"
                >
                  >
                </el-input>
              </el-col>
            </el-form-item>
            <el-form-item>
              <el-col
                class="btn"
                :span="2"
                style="margin-top: 16px; margin-left: -330px"
              >
                <el-button type="primary" @click="doSearch" size="small"
                  >查询</el-button
                >
              </el-col>
            </el-form-item>
            <el-form-item>
              <el-col
                class="btn"
                :span="4"
                style="margin-top: 16px; margin-left: -250px"
              >
                <el-button type="primary" @click="outPut" size="small"
                  >导出明细</el-button
                >
              </el-col>
            </el-form-item>
          </el-form>
        </el-row>
      </div>
      <!-- echarts 图表-->
      <el-row>
        <h3
          style="
            padding: 30px 30px 30px 30px;
            background-color: rgb(242, 242, 242);
          "
        >
          累计销售额人数分布占比
        </h3>
      </el-row>
      <el-row>
        <!-- <h3  style="background-color:rgb(242,242,242)">单人累计消费总额</h3> -->
        <h3 style="margin-top: -2px"></h3>
      </el-row>
      <el-row>
        <el-col class="line1">
          <div
            class="chart"
            ref="chartOne"
            :style="{ width: '1020px', height: '360px' }"
          ></div>
        </el-col>
        <el-col>
          <h3 style="margin-top: 6px; background-color: white"></h3>
        </el-col>
      </el-row>
      <el-col>
        <h3
          style="
            padding-left: 30px;
            padding-top: 30px;
            padding-bottom: 30px;
            background-color: #f2f2f2;
          "
        >
          明细数据
        </h3>
      </el-col>
      <el-col>
        <h1 style="background-color: white; margin-top: -30px"></h1>
      </el-col>
      <!--table -->
      <el-col class="grey">
        <el-table
          :data="tableData"
          :header-cell-class-name="headerStyle"
          style="width: 100%"
        >
          <el-table-column
            prop="section"
            label="价格区间"
            align="center"
            width="350"
          >
          </el-table-column>
          <el-table-column
            prop="userNum"
            label="下单用户总数"
            align="center"
            width="350"
          >
          </el-table-column>
          <el-table-column
            width="350"
            prop="consumeSum"
            align="center"
            label="消费金额合计"
          >
              <template slot-scope="scope">
                 {{Number(scope.row.consumeSum)/100}}
              </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-card>
    <!--分页 -->
    <!-- <el-pagination
          style="text-align: right; margin-top: 20px"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          :page-sizes="[5,10, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination> -->
  </div>
</template>

<script>
import paymentApi from "@/api/lejv/model";
import _ from "lodash"; //引入lodash
import { initTime } from "@/utils/index"; //引入时间处理函数
import { paymentList, exportList } from "@/api/lejv/model";

// 引入 ECharts 主模块
let echarts = require("echarts/lib/echarts");
// 引入柱状图
require("echarts/lib/chart/bar");
// 引入折线图
require("echarts/lib/chart/line");
// 引入提示框和标题组件
require("echarts/lib/component/tooltip");
require("echarts/lib/component/title");
require("echarts/lib/component/legend");
export default {
  name: "order",
  data() {
    return {
      pageNum: 1,
      pageSize: 999,
      total: 0,
      ruleForm: {
        step: "10",
      },
      rules: {
        step: [
          { required: true, message: "请选择价格价格步长", trigger: "blur" },
        ],
      },
      tableData: [
        //  {
        //     date: '0--10',
        //     name: 123,
        //     address: 12323.23
        //   }, {
        //     date: '10-20',
        //     name: 321,
        //     address: 23312.34
        //   }, {
        //     date: '20-30',
        //     name: 453,
        //     address: 12323.23
        //   }, {
        //     date: '30-40',
        //     name: 3455,
        //     address: 12334.23
        //   },
        //    {
        //     date: '40-50',
        //     name: 453,
        //     address: 12323.23
        //   }, {
        //     date: '50-60',
        //     name: 3455,
        //     address: 12334.23
        //   },
        //   {
        //     date: '60-70',
        //     name: 3455,
        //     address: 12334.23
        //   },
        //   {
        //     date: '70-80',
        //     name: 3455,
        //     address: 12334.23
        //   },
        //   {
        //     date: '90-100',
        //     name: 3455,
        //     address: 12334.23
        //   }
      ],
      finalValue: "",
      orderAllTime: [],
      search: {
        orderStartTime: "0",
        orderEndTime: "",
      },
      index: "",
      loading: false,
      earchtsdata: [],
      series: [],
      seriesdata: [],
      sum: 0,
    };
  },
  computed: {},

  created() {},
  mounted() {
    // this.seriesdata=[]
    this.paymentList();
    this.createChartOne();
  },
  methods: {
    //调接口
    async paymentList() {
      // try {
      let prarms = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        startTime: this.search.orderStartTime ? this.search.orderStartTime :"" ,
        endTime: this.search.orderEndTime ? this.search.orderEndTime :"" ,
        step: this.ruleForm.step,
        finalValue: this.ruleForm.step * 10,
      };

      const res = await paymentApi.paymentList(prarms);
      if (res.msg == "success") {
        this.seriesdata = [];
        this.series = [];
        this.earchtsdata = [];
        this.tableData = [];

        if (res.data) {
          this.tableData = JSON.parse(JSON.stringify(res.data.payments));
          // this.tableData = JSON.parse(JSON.stringify(this.tableData));
          // console.log(this.tableData);
          this.total = res.data.totalElements;

          for (let i = 0; i < this.tableData.length; i++) {
            this.earchtsdata.push(this.tableData[i].section);
            this.series.push(this.tableData[i].userNum);
          }
          // console.log(this.series);
        }

        this.getdata();
        // console.log(this.sum, this.seriesdata);
      }
      // }
      //     catch(err){
      //         console.log(err)
      // }
      this.createChartOne();
    },
    //处理百分比
    getdata() {
      let num = 0,
        new_arr = [];
      for (let i = 0; i < this.series.length; i++) {
        num += Number(this.series[i]);
        this.sum = num;
      }

      for (let i = 0; i < this.series.length; i++) {
        new_arr.push(((Number(this.series[i]) / this.sum) * 100).toFixed(2));
        this.seriesdata = JSON.parse(JSON.stringify(new_arr));
      }
      num = 0;
      new_arr = [];
    },

    createChartOne() {
      let chartOne = echarts.init(this.$refs.chartOne);
      chartOne.setOption({
        color: ["#3398DB"],
        title: {
          //  text: "各消费金额用户占比",
          subtext: '各消费金额用户占比',
          // textStyle:{
          //   color:'#333',
          //   fontsize:5,
          //   fontStyle: 'normal' ,
          //   fontWeight: 'normal' ,
          // }
        },
        tooltip: {
          trigger: "axis",
          show: true,

          formatter: function (data) {
            //  console.log(data)
            return (
              "价格区间" +
              ":" +
              data[0].name +
              "</br>" +
              "百分比" +
              ":" +
              data[0].data +
              "%"
            );
          },
        }, // 提示框组件
        grid: {
          left: "3%",
          right: "10%",
          bottom: "3%",
          containLabel: true,
        }, //直角坐标系内绘图网格
        legend: {
          //图例组件
          //  orient: 'vertical',   // 'horizontal' ¦ 'vertical'
          // data: ['2011年'],
          show: true,
          // x: 'center',
        },
        xAxis: {
          type: "value",
          boundaryGap: [0, 0.1],
          name: "人数占比",
          nameTextStyle: {
            padding: [-10, -180, -60, -20], // 四个数字分别为上右下左与原位置距离
          },
        },
        yAxis: {
          type: "category",
          //data: ['0-10', '10-20', '20-30', '30-40', '40-50', '50-60','60-70','70-80','80-90','90-100','100及以上'],
          data: this.earchtsdata,
        },
        series: [
          {
            // name: '2011年',
            type: "bar",
            // data: [10, 20, 21, 10, 13, 8,4,14],
            data: this.seriesdata,

            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: "inside", //数据在中间显示
                  formatter: "{c}%", //百分比显示，模板变量有 {a}、{b}、{c}、{d}，分别表示系列名，数
                },
              },
            },
          },
        ],
      });
    },

    selectTime(e) {
      this.search.orderStartTime = e ? initTime(new Date(e[0]).toJSON()) : "";
      this.search.orderEndTime = e ? initTime(new Date(e[1]).toJSON()) : "";
      // let newTime = new Date(e);
    },
    provingstep(e) {
      // 先把非数字的都替换掉，除了数字和.
      this.ruleForm.step = this.ruleForm.step.replace(/[^\d.]/g, "");
      // 必须保证第一个为数字而不是.
      this.ruleForm.step = this.ruleForm.step.replace(/^\./g, "");
      // 保证只有出现一个.而没有多个.
      this.ruleForm.step = this.ruleForm.step.replace(/\.{2,}/g, "");
      // 保证.只出现一次，而不能出现两次以上
      this.ruleForm.step = this.ruleForm.step
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      let index = -1;
      for (let i in this.ruleForm.step) {
        if (this.ruleForm.step[i] === ".") {
          index = i;
        }
        if (index !== -1) {
          if (i - index > 1) {
            this.ruleForm.step = this.ruleForm.step.substring(
              0,
              this.ruleForm.step.length - 1
            );
          }
        }
      }
    },
    doSearch() {
      this.seriesdata = [];
      this.series = [];
      this.earchtsdata = [];
      // console.log(this.tableData);
      // console.log(this.seriesdata);

      this.paymentList();
    },
    outPut() {
      let params = {
        startTime: this.search.orderStartTime,
        endTime: this.search.orderEndTime,
        step: this.ruleForm.step,
        finalValue: this.ruleForm.step * 10,
      };

      params = _.pickBy(params, (item) => item); //使用lodash进行过滤参数为空的搜索条件

      paymentApi.exportList(params).then((res) => {
        var elink = document.createElement("a");
        elink.download = "付费情况.xls";
        elink.style.display = "none";
        var blob = new Blob([res], { type: "application/vnd.ms-excel" });
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
      });
    },

    headerStyle({ row, column, rowIndex, columnIndex }) {
      return "tableStyle";
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.paymentList();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.paymentList();
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep.spend{
  .payfee {
  padding: 20px 0 0 20px;

  .flexCenter {
    display: flex;
    align-items: center;
    margin: 20px 20px 0 0;
    span {
      margin-right: 10px;
      font-size: 14px;
      width: 100px;
    }
    .time {
      margin-left: -40px;
    }
  }
  }
  .line1 {
  margin-top: -30px;
  width: l020px;
  height: 440px;
  background-color: #f2f2f2;
  .chart {
    padding-left: 30px;
    margin-top: 30px;
    background-color: white !important;
  }
  }
  .grey {
  height: 100%;
  margin-top: -14px;
  background-color: #f2f2f2;
  padding: 20px 20px 80px 20px;
  }
  .tableStyle {
  background-color: white !important;
  color: black;
  font-weight: 400;
  }
  .el-range-editor--small.el-input__inner {
  width: 420px;
  }
  .el-card__body {
  padding: 0px;
  }

}
</style>
